package com.huawei.rbac.service.impl;

import com.huawei.rbac.domain.Employee;
import com.huawei.rbac.mapper.EmployeeMapper;
import com.huawei.rbac.mapper.PermissionMapper;
import com.huawei.rbac.query.EmployeeQueryObject;
import com.huawei.rbac.result.PageResult;
import com.huawei.rbac.service.IEmployeeService;
import com.huawei.rbac.util.UserContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Transactional
public class EmployeeServiceImpl implements IEmployeeService{

    @Autowired
    private EmployeeMapper mapper;

    @Autowired
    private PermissionMapper permissionMapper;

    public void saveOrUpdate(Employee e,Long[] roleIds) {
        if(e.getId() == null){
            mapper.insert(e);
        }else{
            mapper.updateByPrimaryKey(e);
            //删除旧关系
            mapper.deleteEmpAndRoleRelation(e.getId(), null);
        }

        //保存用户和角色的关系
        if(roleIds != null) {
            for (Long roleId : roleIds) {
                mapper.insertEmpAndRoleRelation(e.getId(), roleId);
            }
        }
    }

    public void delete(Long id) {
         mapper.deleteByPrimaryKey(id);
        //删除旧关系
        mapper.deleteEmpAndRoleRelation(id, null);
    }

    @Transactional(readOnly = true)
    public Employee get(Long id) {
        return mapper.selectByPrimaryKey(id);
    }

    @Transactional(readOnly = true)
    public List<Employee> listAll() {
        return mapper.selectAll();
    }

    @Transactional(readOnly = true)
    public PageResult<Employee> query(EmployeeQueryObject qo) {
        //查总条数
        int count = mapper.selectForCount(qo);

        //总条数不为0的时候查结果集
        if(count == 0){
            return new PageResult<Employee>(qo.getCurrentPage(),qo.getPageSize());
        }
        List<Employee> list = mapper.selectForList(qo);
        return new PageResult<Employee>(list,qo.getCurrentPage(),qo.getPageSize(),count);
    }

    public void login(String name, String password) {
        // 调用方法查询获取出当前对象
        Employee currentEmp = mapper.selectEmployeeByUsernamePassword(name, password);
        if(currentEmp == null){
            // 失败
            throw new RuntimeException("亲!账号或密码错误");
        }
        //成功
        //不能直接使用表现层的api,但是我们可以间接使用
        //可以将表现层的api封装到一个工具中,然后调用工具类的方法来访问表现层的api
        UserContext.setCurrentUser(currentEmp);

        //共享当前用户拥有的权限表达式
        //查询当前用户拥有的权限表达式
        List<String> expressions = permissionMapper.selectExpressionsByEmpId(currentEmp.getId());
        UserContext.setPermissionExps(expressions);

    }
}
